from requests import get
from bs4 import BeautifulSoup as BS
import tkinter as tk
from tkinter import ttk
from time import sleep
from threading import Thread
import webbrowser

huzhuUrl = 'https://fishc.com.cn/bestanswer.php?mod=huzhu&type=undo&fid=173&page='
msg = []
root = tk.Tk()
root.title('互帮互助查询')
root.resizable(0,0)

def isnum(value):
    if value == '':
        return True
    try:
        value = int(value)
    except:
        return False
    else:
        return True

def getHelp(urls):
    ret = []
    for url in urls:
        soup = BS(get(url).text,  'html.parser')
        trs = soup.find('table', class_='huzhu').findAll('tr')
        for each in trs:
            ret.append([each.td.em.getText(), each.td.a.getText(), each.findAll('td')[1].getText().replace('\n', ''), each.findAll('td')[2].getText().replace('\n', ''), each.td.a['href']])
        sleep(int(e2.get()))
    return ret

def draw(m):
    x = tree.get_children()
    for item in x:
        tree.delete(item)
    n = 0
    for each in m:
        tree.insert('', n, text='', values=[str(n+1)]+each[:-1])
        n += 1

def updata():
    Thread(target=up).start()

def up():
    global msg
    urls = []
    for p in range(1, int(e3.get())+1):
        urls.append(huzhuUrl+str(p))
    msg = getHelp(urls)
    draw(msg)
    sleep(int(e1.get()))
    root.after(0, updata)

def ret():
    webbrowser.open(msg[tree.index(tree.selection())][4])

IsNum = root.register(isnum)
tree = ttk.Treeview(root, show='headings')
tree.grid(row=0, column=0, columnspan=8)
tree['columns'] = ('序号', '状态', '标题', '回答数', '时间')
tree.column('序号', width=40)
tree.column('状态', width=60)
tree.column('标题', width=250)
tree.column('回答数', width=50)
tree.column('时间', width=130)
tree.heading('序号', text='序号')
tree.heading('状态', text='状态')
tree.heading('标题', text='标题')
tree.heading('回答数', text='回答数')
tree.heading('时间', text='时间')

vbar = ttk.Scrollbar(root, orient=tk.VERTICAL, command=tree.yview)
tree.configure(yscrollcommand=vbar.set)
vbar.grid(row=0, column=8, sticky='NS')

tk.Button(root, text='跳转', command=ret, width=60).grid(row=2, column=0, columnspan=7)

tk.Label(root, text='', width=3).grid(row=3, column=0)

tk.Label(root, text='刷新间隔（秒）：').grid(row=3, column=1)
e1 = tk.Entry(root, width=10, validate='key', validatecommand=(IsNum, '%P'))
e1.grid(row=3, column=2)
e1.insert(0, "20")

tk.Label(root, text='爬取间隔（秒）：').grid(row=3, column=3)
e2 = tk.Entry(root, width=10, validate='key', validatecommand=(IsNum, '%P'))
e2.grid(row=3, column=4)
e2.insert(0, "2")

tk.Label(root, text='翻页数：').grid(row=3, column=5)
e3 = tk.Entry(root, width=10, validate='key', validatecommand=(IsNum, '%P'))
e3.grid(row=3, column=6)
e3.insert(0, "2")

tk.Label(root, text='', width=3).grid(row=3, column=7)
tk.Label(root, text='', width=2).grid(row=3, column=8)

root.after(0, updata)
root.mainloop()
